package com.back.controller;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.hutool.core.util.StrUtil;
import com.back.model.dto.MailArgument;
import com.back.model.dto.user.ResetPasswordDTO;
import com.back.model.dto.user.UserUpdatePageDTO;
import com.back.model.entity.User;
import com.back.model.reslut.Result;
import com.back.service.UserService;
import com.back.utils.Redisutils;
import com.back.utils.SendMail;
import com.back.utils.VerificationCodeGenerator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 忘记密码重置
 */

@RestController
@RequestMapping("/pas")
public class ForgotPassWordController {
    @Resource
    private UserService userService;

    @Resource
    private SendMail sendMail;

    @Resource
    private Redisutils redisutils;

    private static ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap();




    /**
     * 忘记密码 找回密码1 查询用户
     *
     */
    @GetMapping("/forgotPas")
    public Result forgotPas(@RequestParam("userName") String userName) {
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, userName));
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return Result.successData(user.getEmail());
    }


    /**
     * 发送邮件验证码
     * @param updatePageDTO
     * @return
     */

    @PostMapping("/sendEmail")
    public Result sendEmail(@RequestBody UserUpdatePageDTO updatePageDTO) {
        String oldCode = (String)redisutils.get(updatePageDTO.getId().toString());
        if (oldCode != null){
            return Result.successMessage("验证码未过期,不用重复发送");
        }
        //生成验证
        String code = VerificationCodeGenerator.generateVerificationCode(6);

        // map.put(updatePageDTO.getId(), code);
        redisutils.setVerificationCode(updatePageDTO.getId().toString(),code);
        //发送请求
        sendMail.sendTextMailMessage(new MailArgument("", "projectName", "重置密码验证码", sendMail.creteTemlate("VerificationCode.html",code)));
        return Result.success();
    }


    /**
     *核实验证吗
     */
    @GetMapping("/verifyCode")
    public Result verifyCode( @RequestParam("id") @NotNull(message = "id不能为空") Integer id,
                              @RequestParam("code") @NotNull(message = "code不能为空") String code) {
        //核实验证码
        // String verOld = map.get(id);
        String   verOld = (String)redisutils.get(id.toString());
        if (verOld ==null || !verOld.equals(code)){
            throw new RuntimeException("验证码错误");
        }
        return Result.success();
    }


    /**
     * 重置密码
     */
    @PostMapping("/resetPassWord")
    public Result resetPassWord(@RequestBody ResetPasswordDTO resetPasswordDTO) {

        if (!resetPasswordDTO.getNewPassword().equals(resetPasswordDTO.getCheckPassword())) {
            throw new RuntimeException("两次密码不一致");
        }
        User user = new User();
        user.setId(resetPasswordDTO.getId());
        if (StrUtil.isEmpty(resetPasswordDTO.getUserName())){
            User dbUser = userService.getById(resetPasswordDTO.getId());
            resetPasswordDTO.setUserName(dbUser.getUserName());
        }
        user.setPassWord(SaSecureUtil.md5(resetPasswordDTO.getNewPassword() + resetPasswordDTO.getUserName()));
        return userService.updateById(user)? Result.successMessage("重置密码成功"):Result.faile("重置密码失败");
    }

}
